<?php
/**
 * 如花拼团开源系统 -- 永久免费
 * =========================================================
 * 官方网址：http://www.phps.shop
 * 作者：光爵【API + 后台】 、 小草【小程序 + WAP】
 * QQ 交流群：728615087
 * Version：1.0.0
 */
namespace app\api\model;


use app\lib\exception\BaseException;
use app\lib\exception\SuccessMessage;
use think\Db;

class Strategy extends BaseModel
{
    protected $hidden = ['is_hidden','author','create_time','update_time','delete_time'];

    //文章关联多个分类
    public function categoryContent()
    {
        return $this->hasMany('StrategyType','strategy_id','id');
    }

    //文章关联单个分类
    public function categoryContentOne()
    {
        return $this->hasOne('StrategyType','article_id','id');
    }

    //创建用户行程安排
    public static function CreateOne($post)
    {
        $Strategy = new Strategy;
        $StrategyType_type = new StrategyType();
        Db::startTrans();
        try {
            if(is_array($post['category_content'])) {
                $res = (empty($post['id'])) ? false : true;
                $Strategy->isUpdate($res)->save($post); //直接通过关联模型来新增
                $strategy_id = empty($post['id']) ? $Strategy->id : $post['id'];
                foreach ($post['category_content'] as $key => $value) {
                    if (!empty($value['id']) && !empty($value['content'])) {//有二级分类时
                        $data['id'] = $value['id'];
                        $data['content'] = $value['content'];
                        $data['strategy_id'] = $strategy_id;
                        $StrategyType_type->isUpdate(true)->update($data);
                    } else {
                        $error = '二级分类id或者content不能为空';
                        throw new BaseException();
                    }
                }
            }
            else{
                $error = 'category_content为一维数组形式';
                throw new BaseException();
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();// 回滚事务
            throw new BaseException(['msg' => $error]);
        }
        return json(new SuccessMessage(), 201);
    }

    //获取所有文章，包含分页
    public static function getstrategyByPage($page=1, $size=10,$key='',$where=''){
        if(!empty($key)){
            $data = self::where($where)->where('title','like','%'.$key.'%')
                ->order('create_time desc')->paginate($size,'',['page' => $page]);
        }else{
            $data = self::where($where)->order('create_time desc')
                ->paginate($size,'',['page' => $page]);
        }
        return $data;
    }
}